from Common.Base import Base
from Common.Base import open_browser
from selenium import webdriver

browse_url = 'http://localhost:8080/ecshop/user.php'


class BrowseProductZ(Base):
    """封装表现层:制作定位器的过程"""
    home_loc = ("css selector", "a[class='cur']")  # 首页按钮
    operation_list_loc = ('css selector', "div[class='cat1']>a")  # 首页商品种类的定位器
    goods_num = ('css selector', 'td[class="tdl"]>b')  # 商品数量的定位器
    goods_element = ('css selector', 'div[class="goods-info"]>div[class="goods-title"]>a')  # 具体商品的定位器

    """封装操作层:针对表现层中元素的操作"""

    def click_home(self):
        """
        点击首页
        :return:
        """
        self.click(self.home_loc)

    def get_operation(self):
        """
        获取家用电器,数码时尚,智能硬件....
        :return:
        """
        result = self.find_elements(self.operation_list_loc)
        element_loc = []
        for element in result:
            locator = ("link text", f"{element.text}")
            element_loc.append(locator)
        return element_loc

    def get_goods_loc(self):
        """
        获取商品的元素定位器
        :return:
        """
        result = self.find_elements(self.goods_element)
        element_loc = []
        for element in result:
            locator = ("link text", f"{element.text}")
            element_loc.append(locator)
        return element_loc

    def is_0_goods(self):
        """
        判断商品数量是否为零
        :return:
        """
        return self.get_element_text(self.goods_num)

    def browse_goods(self):
        """
        浏览商品
        :return:
        """
        element_list = self.get_operation()
        try:
            for operation in element_list:
                # 点击操作的元素
                self.click(operation)

                # 判断进入的页面显示的商品数量是否为0
                if self.is_0_goods() == "0":
                    # 为0就返回
                    self.back_z()
                # 不为0就点击浏览商品
                else:
                    result = self.get_goods_loc()
                    for goods in result:
                        self.click(goods)
                        self.back_z()
                    self.back_z()
        except:
            return False
        else:
            return True


if __name__ == '__main__':
    browse = BrowseProductZ(open_browser())
    browse.open_url(browse_url)
    browse.click_home()
    browse.browse_goods()
